#!/bin/sh

set -ex

pkg() {
    if [ "$(id -u)" -eq 0 ] ; then
        command      pkg "$@"
    else
        command sudo pkg "$@"
    fi
}

package_name_transform_from_uppm_to_pkg() {
    case $1 in
        gm4)      printf '%s\n' 'm4'        ;;
        grep)     printf '%s\n' 'gnugrep'   ;;
        golang)   printf '%s\n' 'go122'     ;;
        yq)       printf '%s\n' 'go-yq'     ;;
        xz)       printf '%s\n' 'gtar'      ;;
        bsdtar)   printf '%s\n' 'gtar'      ;;
        ed)       printf '%s\n' 'gsed'      ;;
        pkg-config) printf '%s\n' 'pkgconf' ;;
        perl)     printf '%s\n' 'perl5.38'  ;;
        *)        printf '%s\n' "$1"
    esac
}

main() {
    case $1 in
        about)
            pkg --version
            ;;
        update)
            pkg update
            ;;
        install)
            shift 1
            for UPPM_PACKAGE_NAME in "$@"
            do
                FPKG_PACKAGE_NAME="$(package_name_transform_from_uppm_to_pkg "$UPPM_PACKAGE_NAME")"
                pkg install -y "$FPKG_PACKAGE_NAME"
            done
            ;;
        is-installed)
            shift 1
            FPKG_PACKAGE_NAME="$(package_name_transform_from_uppm_to_pkg "$1")"
            pkg info "$FPKG_PACKAGE_NAME" 2>/dev/null
            ;;
        info)
            shift 1
            case $2 in
                installed-dir)
                    #printf '%s\n' '/usr/local'
                    ;;
            esac
            ;;
        *)  pkg "$@"
    esac
}

main "$@"
